package cn.tqfeiyang.springplus.framework.security;

import cn.tqfeiyang.springplus.framework.Constants;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Collections;
import java.util.Objects;

@Service
public class SecurityServiceImpl implements SecurityService {

    /**
     * 获取授权Token
     *
     * @return 授权Token
     */
    @Override
    public UsernamePasswordAuthenticationToken getAuthenticationToken() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication instanceof UsernamePasswordAuthenticationToken) {
            return (UsernamePasswordAuthenticationToken) authentication;
        } else {
            return null;
        }
    }

    /**
     * 获取当前用户
     *
     * @return 用户信息
     */
    @Override
    public AuthenticationUserDetails getCurrentUser() {
        UsernamePasswordAuthenticationToken token = getAuthenticationToken();
        return Objects.nonNull(token) ? (AuthenticationUserDetails) token.getPrincipal() : null;
    }

    /**
     * 获取用户Id
     *
     * @return 用户id
     */
    @Override
    public Long getUserId() {
        AuthenticationUserDetails currentUser = getCurrentUser();
        return currentUser != null ? currentUser.getId() : 0L;
    }

    /**
     * 获取权限列表
     *
     * @return 权限列表
     */
    @Override
    public Collection<GrantedAuthority> getAuthorities() {
        UsernamePasswordAuthenticationToken token = getAuthenticationToken();
        return Objects.nonNull(token) ? token.getAuthorities() : Collections.emptyList();
    }

    /**
     * 是否拥有对应的权限
     *
     * @param anthority
     * @return boolean
     */
    @Override
    public boolean hasAuthority(String anthority) {
        for (GrantedAuthority authority : getAuthorities()) {
            if (authority.getAuthority().equalsIgnoreCase(Constants.ROLE_ADMIN)) {
                return true;
            }
            if (anthority.equalsIgnoreCase(authority.getAuthority())) {
                return true;
            }
        }

        return false;
    }

    /**
     * 是否拥有列表中的任何一个权限
     *
     * @param authorities
     * @return boolean
     */
    @Override
    public boolean hasAnyAuthority(String... authorities) {
        for (String authority : authorities) {
            if (hasAuthority(authority)) {
                return true;
            }
        }
        return false;
    }
}
